#!python3
from .component import *
import tkinter.messagebox
import tkinter.filedialog
import json
import gui.docSettings as ds

class MainWindow:

    hasSetStyle = {}
    allSet = []
    styles = []
    out = None
    saveFile = ''

    # 读json文件
    def buttonListener2(self, event):
        filename = tkinter.filedialog.askopenfilename()
        MainWindow.saveFile = filename
        with open(filename, mode='r', encoding='utf-8') as f:
            MainWindow.allSet += json.loads(f.read())
            for each in MainWindow.allSet:
                MainWindow.hasSetStyle[each['style']] = MainWindow.allSet.index(each)
        MainWindow.out = MainWindow.allSet[0]
        styles = []
        for each in MainWindow.allSet:
            if len(MainWindow.styles)==0:
                styles.append(each['style'])
            else:
                styles = MainWindow.styles
        self.vStyleList.config(values=styles)
        self.vStyleList.current(0)
        setShowValue(MainWindow.out, self)

    # 写json文件
    def buttonListener3(self, event):
        if MainWindow.saveFile == '':
            filename = tkinter.filedialog.asksaveasfilename(
                defaultextension='.json')
            MainWindow.saveFile = filename
        else:
            filename = MainWindow.saveFile
        if filename != '':
            with open(filename, mode='w', encoding='utf-8') as f:
                json.dump(MainWindow.allSet, f, ensure_ascii=False)
            self.FileSaveCondition.config(text="模板文件"+f.name+"已保存")
        else:
            self.FileSaveCondition.config(text="没有保存模板文件")

    #读取docx文件
    def buttonReadDocx(self, event):
        f = tkinter.filedialog.askopenfilename()
        if f:
            self.FileSelectCondition.config(text="您选择的文件是："+f)
            if self.on.get('importDocx'): 
                config = self.on['importDocx'](f)
                MainWindow.styles = config['styles']
                MainWindow.allSet += config['allSet']
                for each in MainWindow.allSet:
                    MainWindow.hasSetStyle[each['style']] = MainWindow.allSet.index(each)
                self.vStyleList.config(values=MainWindow.styles)
        else:
            self.FileSelectCondition.config(text="您没有选择任何文件")

    #写入docx文件
    def buttonListener5(self, event):
        filename = tkinter.filedialog.asksaveasfilename(
            defaultextension=".docx")
        if filename != '':
            if self.on.get('exportDocx'): self.on['exportDocx'](filename,MainWindow.allSet)
            self.FileSelectCondition.config(text="docx文件"+filename+"已导出")
        else:
            self.FileSelectCondition.config(text="没有导出文件")


    '''def button1P(self):
        self.button1 = self.createButton("新建模板") #Button(self.frame,text = "新建模板",width = 10,height = 1)
        self.button1.grid(row = 0,column = 0,padx = 5,pady = 5)
        self.button1.bind("<ButtonRelease-1>",self.buttonListener1)'''
    
    '''def button2P(self):
            # Button(self.frame,text = "从已有模板导入",width = 10,height = 1)
            self.button2 = self.createButton("从已有模板导入")
            self.button2.pack()
            self.button2.bind("<ButtonRelease-1>", self.buttonListener2)
    def button3P(self):
            self.button3 = self.createButton("保存模板文件")
            self.button3.pack()
            self.button3.bind("<ButtonRelease-1>", self.buttonListener3)'''
    def moban(self):#模板导入导出按钮组
        p = Frame(self.frame)
        p.pack()
        self.button2 = createButton(p,"从已有模板导入")
        self.button2.grid(row=0, column=0, padx=3, pady=3)
        self.button2.bind("<ButtonRelease-1>", self.buttonListener2)
        self.button3 = createButton(p,"保存模板文件")
        self.button3.grid(row=0, column=1, padx=3, pady=3)
        self.button3.bind("<ButtonRelease-1>", self.buttonListener3)
    def exchange(self):#docx文件导入导出按钮组
        p = Frame(self.frame)
        p.pack()
        self.button4 = createButton(p,"导入docx")
        self.button4.grid(row=0, column=0, padx=3, pady=3)
        self.button4.bind("<ButtonRelease-1>", self.buttonReadDocx)
        self.button5 = createButton(p,"导出docx")
        self.button5.grid(row=0, column=1, padx=3, pady=3)
        self.button5.bind("<ButtonRelease-1>", self.buttonListener5)
    '''def button4P(self):
        self.button4 = self.createButton("导入docx")
        self.button4.pack()
        self.button4.bind("<ButtonRelease-1>", self.buttonReadDocx)

    def button5P(self):
        self.button5 = self.createButton("导出docx")
        self.button5.pack()
        self.button5.bind("<ButtonRelease-1>", self.buttonListener5)'''

    def selectType(self):  # 文字类型
        def go(*args):  # 处理事件，*args表示可变参数
            nowStyle = comboxlist.get()
            index = MainWindow.hasSetStyle.get(nowStyle)
            print('select index',index,nowStyle)
            if index == None:
                MainWindow.out = {'style':nowStyle}
                MainWindow.hasSetStyle[nowStyle] = len(MainWindow.allSet)
                MainWindow.allSet.append(MainWindow.out)
            else:
                MainWindow.out = MainWindow.allSet[index]
            print('select out',MainWindow.out)
            setShowValue(MainWindow.out,self)
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(self.frame, [])
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        comboxlist.pack()
        #comboxlist.current(0)  # 选择第一个
        self.vStyleList = comboxlist

    def selectFontFace(self, frame):  # 字体
        p = Frame(frame)

        def go(*args):  # 处理事件，*args表示可变参数
            MainWindow.out['Font'] = comboxlist.get()
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(
            p, ["宋体", "黑体", "楷体", "微软雅黑", "幼圆", "隶书"])
        comboxlist.grid(row=0, column=1, padx=3, pady=3)
        Label(p, text="字体类型").grid(row=0, column=0, padx=3, pady=3)
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        self.vFontList = comboxlist
        return p

    def selectFontSize(self, frame):  # 字体大小
        p = Frame(frame)

        def go(*args):  # 处理事件，*args表示可变参数
            MainWindow.out['FontSize'] = comboxlist.get()
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(p, ["二号", "小二", "三号", "小三", "四号", "小四"])
        comboxlist.grid(row=0, column=1, padx=3, pady=3)
        Label(p, text="字体大小").grid(row=0, column=0, padx=3, pady=3)
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        self.vFontSizeList = comboxlist
        return p

    def fontJudgePane(self):
        pane = Frame(self.frame)
        pane.pack()

        def go(b):
            MainWindow.out['bold'] = b

        def go1(i):
            MainWindow.out['italic'] = i

        def go2(u):
            MainWindow.out['underline'] = u

        self.boldCheckButton = createCheckButton(
            pane, "B", True, 2, outside=go)
        self.boldCheckButton.grid(row=0, column=0)
        self.italicCheckButton = createCheckButton(
            pane, "I", True, 2, outside=go1)
        self.italicCheckButton.grid(row=0, column=1)
        self.underlineCheckButton = createCheckButton(
            pane, "U", True, 2, outside=go2)
        self.underlineCheckButton.grid(row=0, column=2)

    def createempty(self):
        def go(empty):
            MainWindow.out['在相同样式的段落间不添加空格'] = empty
        self.isbold = createCheckButton(
            self.frame, "在相同样式的段落间不添加空格", True, outside=go)
        self.isbold.pack()
        self.v4List = self.isbold

    def retainFormat(self):
        def go(retain):
            MainWindow.out['保留原有特殊格式'] = retain
        self.isbold = createCheckButton(
            self.frame, "保留原有特殊格式", True, outside=go)
        self.isbold.pack()
        self.v5List = self.isbold

    def selectCodeType(self):  # 符号类型
        p = Frame(self.frame)

        def go(*args):  # 处理事件，*args表示可变参数
            MainWindow.out['SymbolType'] = comboxlist.get()
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(p, ["中文", "西文"])
        comboxlist.grid(row=0, column=1, padx=3, pady=3)
        Label(p, text="符号类型").grid(row=0, column=0, padx=3, pady=3)
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        p.pack()
        self.vSymbolTypeList = comboxlist

    def selectAlignWay(self):  # 对齐方式
        p = Frame(self.frame)

        def go(*args):  # 处理事件，*args表示可变参数
            MainWindow.out['Alignment'] = comboxlist.get()
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(
            p, ["靠左对齐", "靠右对齐", "居中对齐", "两端对齐"])
        comboxlist.grid(row=0, column=1, padx=3, pady=3)
        Label(p, text="对齐方式").grid(row=0, column=0, padx=3, pady=3)
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        p.pack()
        self.vAlignmentList = comboxlist

    def selectSpecialType(self):  # 特殊格式
        p = Frame(self.frame)

        def go(*args):  # 处理事件，*args表示可变参数
            MainWindow.out['SpecialFormat'] = comboxlist.get()
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(p, ["首行缩进", "悬挂缩进"])
        comboxlist.grid(row=0, column=1, padx=3, pady=3)
        Label(p, text="特殊格式").grid(row=0, column=0, padx=3, pady=3)
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        p.pack()
        self.vSpecialFormatList = comboxlist

    def createLeft(self,frame):  # 左缩进
        def go(value):
            MainWindow.out['leftPadding'] = value
        p = Frame(frame)
        left = selectWithUnit(p, ds.unit, go)
        left.grid(row=0, column=1, padx=3, pady=3)
        zuoce = Label(p, text="左侧:")
        zuoce.grid(row=0, column=0, padx=3, pady=3)
        self.leftPaddingList = left
        return p

    def createRight(self,frame):  # 右缩进
        def go(value):
            MainWindow.out['rightPadding'] = value
        p = Frame(frame)
        right = selectWithUnit(p, ds.unit, go)
        right.grid(row=0, column=1, padx=3, pady=3)
        youce = Label(p, text="右侧:")
        youce.grid(row=0, column=0, padx=3, pady=3)
        self.rightPaddingList = right
        return p

    def createsuojinValue(self):  # 缩进值
        def go(value):
            MainWindow.out['indented'] = value
        p = Frame(self.frame)
        suojin = selectWithUnit(p, ds.unit, go)
        suojin.grid(row=0, column=1, padx=3, pady=3)
        suojinValue = Label(p, text="缩进值:")
        suojinValue.grid(row=0, column=0, padx=3, pady=3)
        p.pack()
        self.indentedList = suojin

    def createduanqianValue(self,frame):  # 段前值
        def go(value):
            MainWindow.out['beforeParagraph'] = value
        p = Frame(frame)
        duanqian = selectWithUnit(p, ds.unit, go)
        duanqian.grid(row=0, column=1, padx=3, pady=3)
        duanqianL = Label(p, text="段前:")
        duanqianL.grid(row=0, column=0, padx=3, pady=3)
        self.beforePList = duanqian
        return p

    def createduanhouValue(self,frame):  # 段后值
        def go(value):
            MainWindow.out['afterParagraph'] = value
        p = Frame(frame)
        duanhou = selectWithUnit(p, ds.unit, go)
        duanhou.grid(row=0, column=1, padx=3, pady=3)
        duanhouL = Label(p, text="段后:")
        duanhouL.grid(row=0, column=0, padx=3, pady=3)
        self.afterPList = duanhou
        return p

    def selectHangjuType(self):  # 行距类型
        p = Frame(self.frame)

        def go(*args):  # 处理事件，*args表示可变参数
            MainWindow.out['LineSpacingType'] = comboxlist.get()
            print(comboxlist.get())  # 打印选中的值
        comboxlist = createSelectInput(
            p, ["单倍行距", "1.5倍行距", "2倍行距", "最小值", "固定值", "多倍行距"])
        comboxlist.grid(row=0, column=1, padx=3, pady=3)
        Label(p, text="特殊格式").grid(row=0, column=0, padx=3, pady=3)
        # 绑定事件,(下拉列表框被选中时，绑定go()函数)
        comboxlist.bind("<<ComboboxSelected>>", go)
        p.pack()
        self.vLineSpacingTypeList = comboxlist

    def createHangjuValue(self):  # 行距设置值
        def go(value):
            MainWindow.out['lineSpacing'] = value
        p = Frame(self.frame)
        shezhivalue = selectWithUnit(p, ds.unit, go)
        shezhivalue.grid(row=0, column=1, padx=3, pady=3)
        shezhivalueL = Label(p, text="设置值:")
        shezhivalueL.grid(row=0, column=0, padx=3, pady=3)
        p.pack()
        self.lineSpacingValueList = shezhivalue

        #页边距
    def createtop(self,frame):
        def go(value):
            MainWindow.out['pageMarginsTop'] = value
        p = Frame(frame)
        top = selectWithUnit(p, ds.unit, go)
        top.grid(row=0, column=1, padx=3, pady=3)
        shang = Label(p, text="上:")
        shang.grid(row=0, column=0, padx=3, pady=3)
        self.pMtopList = top
        return p
    def createbuttom(self,frame):
        def go(value):
            MainWindow.out['pageMarginsButtom'] = value
        p = Frame(frame)
        buttom = selectWithUnit(p, ds.unit, go)
        buttom.grid(row=0, column=1, padx=3, pady=3)
        xia = Label(p, text="下:")
        xia.grid(row=0, column=0, padx=3, pady=3)
        self.pMbuttomList = buttom
        return p
    def createLeftSide(self,frame):
        def go(value):
            MainWindow.out['pageMarginsLeftSide'] = value
        p = Frame(frame)
        LeftSide = selectWithUnit(p, ds.unit, go)
        LeftSide.grid(row=0, column=1, padx=3, pady=3)
        zuo = Label(p, text="左:")
        zuo.grid(row=0, column=0, padx=3, pady=3)
        self.pMLeftSideList = LeftSide
        return p
    def createRightSide(self,frame):
        def go(value):
            MainWindow.out['pageMarginsRightSide'] = value
        p = Frame(frame)
        RightSide = selectWithUnit(p, ds.unit, go)
        RightSide.grid(row=0, column=1, padx=3, pady=3)
        you = Label(p, text="右:")
        you.grid(row=0, column=0, padx=3, pady=3)
        self.pMRightSideList = RightSide
        return p

    def __init__(self,onImportDocx=None,onExportDocx=None):
        self.on = {}
        if onImportDocx != None: self.on['importDocx'] = onImportDocx
        if onExportDocx != None: self.on['exportDocx'] = onExportDocx
        self.frame = Tk()
        self.frame.geometry('500x700')
        #root = self.frame
        self.frame.title("docx格式器")
        # self.button1P()
        #self.button2P()
        self.moban()
        self.selectType()

        fontPane = Frame(self.frame)
        fontFace = self.selectFontFace(fontPane)
        fontFace.grid(row=0, column=0, padx=3, pady=3)
        fontSize = self.selectFontSize(fontPane)
        fontSize.grid(row=0, column=1, padx=3, pady=3)
        fontPane.pack()
        # self.checkBold()
        # self.checkItale()
        # self.checkUnderLine()
        self.fontJudgePane()
        yebianju = Label(self.frame, text="页边距")
        yebianju.pack()

        spacingPane1 = Frame(self.frame)
        spacingTop= self.createtop(spacingPane1)
        spacingTop.grid(row=0, column=0, padx=3, pady=3)
        spacingButtom= self.createbuttom(spacingPane1)
        spacingButtom.grid(row=0, column=1, padx=3, pady=3)
        spacingPane1.pack()

        spacingPane2 = Frame(self.frame)
        spacingLeft= self.createLeftSide(spacingPane2)
        spacingLeft.grid(row=0, column=0, padx=3, pady=3)
        spacingRight= self.createRightSide(spacingPane2)
        spacingRight.grid(row=0, column=1, padx=3, pady=3)
        spacingPane2.pack()

        self.selectAlignWay()
        self.selectCodeType()
        suojin = Label(self.frame, text="缩进")
        suojin.pack()

        self.selectSpecialType()

        suojinPane = Frame(self.frame)
        suojinLeft=self.createLeft(suojinPane)
        suojinLeft.grid(row=0, column=0, padx=3, pady=3)
        suojinRight=self.createRight(suojinPane)
        suojinRight.grid(row=0, column=1, padx=3, pady=3)
        suojinPane.pack()

        self.createsuojinValue()
        jianju = Label(self.frame, text="间距")
        jianju.pack()

        jianjuPane =Frame(self.frame)
        duanqian=self.createduanqianValue(jianjuPane)
        duanqian.grid(row=0, column=0, padx=3, pady=3)
        duanhou=self.createduanhouValue(jianjuPane)
        duanhou.grid(row=0, column=1, padx=3, pady=3)
        jianjuPane.pack()

        self.selectHangjuType()

        self.createHangjuValue()
        self.createempty()
        self.retainFormat()

        self.FileSaveCondition = Label(self.frame)
        self.FileSaveCondition.pack()
        #self.button3P()

        self.FileSelectCondition = Label(self.frame)
        self.FileSelectCondition.pack()
        #self.button4P()
        #self.button5P()
        self.exchange()
        self.frame.mainloop()
        print(MainWindow.out)


def main():
    MainWindow()


if __name__ == '__main__':
    main()
